import os
import logging
from .api import all_api_router
from .config import pkgm_config, server_root_dir
from .system_event import startup, stopping
from fastapi import FastAPI, Request
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from starlette.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware

LOG = logging.getLogger(__name__)


application = FastAPI(
    debug=os.getenv("APP_DEBUG") == "True" or False,
    title=pkgm_config.show_title,
    description=pkgm_config.description,
    docs_url=None,
    redoc_url=None,
    swagger_ui_oauth2_redirect_url="/docs/oauth2-redirect"
)
application.openapi_version = "3.0.0"


def start_init_app():
    application.add_middleware(
        CORSMiddleware,
        allow_origins=pkgm_config.cors_origns,
        allow_credentials=pkgm_config.cors_allow_credentials,
        allow_methods=pkgm_config.cors_allow_methods,
        allow_headers=pkgm_config.cors_allow_headers,
    )
    application.mount('/', StaticFiles(directory=server_root_dir), name="public")
    # application.mount('/resource/', StaticFiles(directory=pkgm_config.static_dir), name="resource")

    application.add_event_handler("startup", startup(application))
    application.add_event_handler("shutdown", stopping(application))


def open_dev_doc(app: FastAPI):
    app.get("/docs", include_in_schema=False)(custom_swagger_ui_html)
    app.get("/redoc", include_in_schema=False)(redoc_html)


def custom_swagger_ui_html(req: Request):
    return get_swagger_ui_html(
        openapi_url=req.app.openapi_url,
        title=req.app.title + " - Swagger UI",
        oauth2_redirect_url=req.app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/swagger/swagger-ui-bundle.js",
        swagger_css_url="/swagger/swagger-ui.css"
    )


def redoc_html(req: Request):
    return get_redoc_html(
        openapi_url=req.app.openapi_url,
        title=req.app.title + "- ReDoc",
        redoc_js_url="/redoc/redoc.standalone.js"
    )

if pkgm_config.run_model == "debug":
    open_dev_doc(application)

application.include_router(all_api_router)
